package com.beiding.businessplatform.data;

import java.util.HashSet;
import java.util.Set;

public class SubVmUnit implements CacheUnit<Vm> {


    private Vm vm;
    private String field;
    private Vm subVm;

    public SubVmUnit(Vm vm, String field) {
        this.vm = vm;
        this.field = field;
    }

    /*
        外部类不能处理内部类
     */

    @Override
    public void write(Set<Vm> vmPath) {
        vmPath.add(vm);
        if (vmPath.contains(subVm)) {//TODO 防止无限递归
            return;
        }
        //TODO 应该返回Be对象
        HolderMap map = vm.holderMap();
        Holder holder = map.get(this.field);
        Be v = (Be) holder.get();
        if (v == null) {
            if (subVm != null) {
                VmCache vmCache = subVm.vmCache();
                v = vmCache.handle(vmPath);
                holder.set(v);
            }
        } else {
            if (subVm == null) {
                holder.set(null);
            } else {
                VmCache vmCache = subVm.vmCache();
                Be targetBe = subVm.be();
                if (targetBe != v) {
                    vmCache.handle(v, vmPath);
                }
            }
        }
        vmPath.remove(vm);
    }

    @Override
    public Vm read() {
        return subVm;
    }

    public void update(Vm value) {
        this.subVm = value;
        write(new HashSet<>());
    }

    public void setSubVm(Vm subVm) {
        this.subVm = subVm;
    }
}
